<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--公司数据-->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-tree
            :data="companydata"
            default-expand-all
            :expand-on-click-node="false"
            node-key="companyId"
            ref="tree"
            highlight-current
            :props="defaultProps"
            @node-click="getCheckedKeys"
          />
        </div>
      </el-col>
      <el-col :span="20" :xs="24">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch">
          <el-form-item label="部门名称" prop="deptName">
            <el-input
              v-model="queryParams.deptName"
              placeholder="请输入部门名称"
              clearable
              size="default"
              @keyup.enter="handleQuery"
              style="width: 240px"
            />
          </el-form-item>
          <el-form-item label="部门状态" prop="status">
            <el-select
              v-model="queryParams.status"
              placeholder="部门状态"
              clearable
              size="default"
              style="width: 240px"
            >
              <el-option
                v-for="dict in statusOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <search-button @click="handleQuery" :perm="['system:dept:search']" />
            <reset-button @click="resetQuery" :perm="['system:dept:search']" />
          </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8">
          <add-button @click="handleAdd" :perm="['system:dept:insert']" />
          <right-toolbar
            v-model:showSearch="showSearch"
            @query-table="getList"
            :perm="['system:dept:search']"
          />
        </el-row>
        <el-table
          v-loading="loading"
          :data="deptList"
          row-key="deptId"
          default-expand-all
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        >
          <el-table-column prop="deptName" label="部门名称" min-width="180" />
          <el-table-column prop="deptCode" label="部门编码" min-width="80" />
          <el-table-column prop="deptShortname" label="简称" min-width="120" />
          <el-table-column
            prop="deptType"
            label="部门类型"
            :formatter="deptTypeFormat"
            width="120"
          />
          <el-table-column label="所属公司" width="240" align="center">
            <template #default="scope">
              <span>{{ scope.row.companyName + '(' + scope.row.companyCode + ')' }}</span>
            </template>
          </el-table-column>
          <ExtColTableColumn tableName="sys_dept" />
          <el-table-column prop="status" label="状态" width="80">
            <template #default="scope">
              <span :class="scope.row.status === 'N' ? 'text-danger' : ''">{{
                selectDictLabel(statusOptions, scope.row.status)
              }}</span>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" align="center" prop="createTime" width="160">
            <template #default="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
            width="200"
          >
            <template #default="scope">
              <text-add-button @click="handleAdd(scope.row)" :perm="['system:dept:insert']" />
              <text-edit-button @click="handleUpdate(scope.row)" :perm="['system:dept:update']" />
              <text-delete-button
                @click="handleDelete(scope.row)"
                :perm="['system:dept:delete']"
                :title="'是否确认删除' + scope.row.deptName + '?'"
              />
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>

    <!-- 添加或修改参数配置对话框 -->
    <drag-dialog      
      :title="title"
      :close-on-click-modal="false"
      v-model="open"
      width="800px"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="所属公司">
              <span>{{ form.companyName }}({{ form.companyCode }})</span>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="上级部门" prop="parentId">
              <el-tree-select v-model="form.parentId" :data="deptList" check-strictly
                :render-after-expand="false" :props="{ value: 'deptId', label: 'deptName', children: 'children' }"
                placeholder="请选择上级部门" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门名称" prop="deptName">
              <el-input v-model="form.deptName" placeholder="请输入部门名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门编码" prop="deptCode">
              <el-input v-model="form.deptCode" placeholder="请输入部门编码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="简称" prop="deptShortname">
              <el-input v-model="form.deptShortname" placeholder="请输入简称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示排序" prop="orderNum">
              <el-input-number v-model="form.orderNum" controls-position="right" :min="1" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门类型">
              <el-radio-group v-model="form.deptType">
                <el-radio
                  v-for="dict in deptTypeOptions"
                  :key="dict.dictValue"
                  :value="dict.dictValue"
                >{{ dict.dictLabel }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门级别">
              <el-radio-group v-model="form.deptLevel">
                <el-radio
                  v-for="dict in deptLevelOptions"
                  :key="dict.dictValue"
                  :value="dict.dictValue"
                >{{ dict.dictLabel }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="负责人" prop="leader">
              <el-input v-model="form.leader" placeholder="请输入负责人" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入联系电话" maxlength="11" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" placeholder="请输入邮箱" maxlength="50" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-radio-group v-model="form.status">
                <el-radio v-for="dict in statusOptions" :key="dict.value" :value="dict.dictValue">{{
                  dict.dictLabel
                }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <ExtColFormItem tableName="sys_dept" :form="form" :span="12" />
      </el-form>
      <template #footer>
        <dialog-footer @ok="submitForm" @cancel="cancel" />
      </template>
    </drag-dialog>
  </div>
</template>

<script>
import { listDept, getDept, addDept, updateDept, delDept } from '@base/api/base/dept'
import { listCompany } from '@base/api/base/company'
import { debounceWrapper } from '@/utils/zmids'

export default {
  name: 'BaseDept',
  data() {
    return {
      selectOption: undefined,
      //公司信息
      companydata: [],
      defaultProps: {
        children: 'children',
        label: 'companyName'
      },
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格树数据
      deptList: [],
      // 机构树选项
      orgOptions: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 状态数据字典
      statusOptions: [],
      // 部门类型
      deptTypeOptions: [],
      // 部门级别
      deptLevelOptions: [],
      // 查询参数
      queryParams: {
        companyId: undefined,
        deptName: undefined,
        status: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        // parentId: [
        //   { required: true, message: "上级部门不能为空", trigger: "blur" }
        // ],
        deptName: [{ required: true, message: '部门名称不能为空', trigger: 'blur' }],
        deptCode: [{ required: true, message: '部门编码不能为空', trigger: 'blur' }],
        orderNum: [{ required: true, message: '菜单顺序不能为空', trigger: 'blur' }],
        email: [
          {
            type: 'email',
            message: "'请输入正确的邮箱地址",
            trigger: ['blur', 'change']
          }
        ],
        phone: [
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: '请输入正确的手机号码',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created() {
    //初始化查询
    this.getCompanyList()
    this.getList()
    //初始化数据字典
    this.getDicts('sys_normal_disable').then((response) => {
      this.statusOptions = response.data
    })
    this.getDicts('sys_dept_type').then((response) => {
      this.deptTypeOptions = response.data
    })
    this.getDicts('sys_dept_level').then((response) => {
      this.deptLevelOptions = response.data
    })
  },
  methods: {
    getCheckedKeys(companydata) {
      this.selectOption = companydata
      this.getList()
    },
    getCompanyList: debounceWrapper(function () {
      this.loading = true
      listCompany(this.queryParams).then((response) => {
        this.companydata = response.data
        this.loading = false
      })
    }),
    /** 查询部门列表 */
    getList: debounceWrapper(function () {
      this.loading = true
      this.queryParams.companyId = this.selectOption && this.selectOption.companyId
      listDept(this.queryParams).then((response) => {
        this.deptList = this.handleTree(response.data, 'deptId')
        this.loading = false
      })
    }),
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.selectOption = undefined
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 字典状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status)
    },
    deptTypeFormat(row, column) {
      return this.selectDictLabel(this.deptTypeOptions, row.deptType)
    },
    deptLevelFormat(row, column) {
      return this.selectDictLabel(this.deptLevelOptions, row.deptLevel)
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        deptId: undefined,
        parentId: undefined,
        deptName: undefined,
        deptCode: undefined,
        deptShortname: undefined,
        orderNum: 1,
        leader: undefined,
        phone: undefined,
        email: undefined,
        deptType: '1',
        deptLevel: '0',
        status: 'Y',
        companyId: undefined
      }
      this.resetForm('form')
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset()
      if (!this.selectOption) {
        this.msgError('请选择一个公司')
        return
      }
      if (row != undefined) {
        this.form.parentId = row.deptId
      }
      this.open = true
      this.title = '添加部门'
      this.form.companyId = this.selectOption && this.selectOption.companyId
      this.form.companyName = this.selectOption && this.selectOption.companyName
      this.form.companyCode = this.selectOption && this.selectOption.companyCode
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      getDept(row.deptId).then((response) => {
        this.form = response.data
        this.open = true
        this.title = '修改部门'
        if (this.form.parentId === 0) {
          this.form.parentId = undefined
        }
      })
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.form.deptId != undefined) {
            if (this.form.parentId != this.form.deptId) {
              updateDept(this.form).then((response) => {
                if (response.data === 1) {
                  this.msgSuccess('修改成功')
                  this.open = false
                  this.getList()
                }
              })
            } else {
              this.msgError('不能选自己作为父级部门')
            }
          } else {
            if (this.form.companyId !== undefined) {
              addDept(this.form).then((response) => {
                if (response.data === 1) {
                  this.msgSuccess('新增成功')
                  this.open = false
                  this.getList()
                }
              })
            } else {
              this.msgError('未选择公司，必须在公司下新建部门')
            }
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      delDept(row.deptId)
        .then(() => {
          this.getList()
          this.msgSuccess('删除成功')
        })
        .catch(function () {})
    }
  }
}
</script>
